package com.example.udp_test;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.UDP_Test.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.SocketException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private Button send;
    private TextView receiveContent;
    private ScrollView scrollView;
    private CommunicateWordsWithUDP transformWords;
    private Handler handler;
    private TextWatcher mTextWatcher;
    private EditText editIPAddr;
    private boolean isIPReady;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //弹框请用户输入IP地址
        showInputIPDialog();
        //监听发送内容输入框
        mTextWatcher = new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(!TextUtils.isEmpty(editText.getText().toString())){
                    send.setClickable(true);
                }else {
                    send.setClickable(false);
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }

        };
        //初始化视图界面
        initView();
        handler=new Handler();


        //获取存储的信息
        SharedPreferences getSharedPreference =getSharedPreferences("save_data",MODE_PRIVATE);
        String data = getSharedPreference.getString("save_data"," ");
        receiveContent.setText(data);

        //发送按钮的点击事件
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String sendContent=editText.getText().toString();
                if(!TextUtils.isEmpty(sendContent)){
                    //用Html控制文字格式
                    receiveContent.append("\n");
                    receiveContent.append(Html.fromHtml("<font><strong><em>我:</em></strong></font>"));
                    receiveContent.append("\n");
                    receiveContent.append(Html.fromHtml("<font>"+sendContent+"</font>"));
                    //使textVIew滑动到最下方显示最新消息
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.fullScroll(View.FOCUS_DOWN);
                        }
                    });
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            transformWords.sendDataWithUDPSocket(sendContent);
                        }
                    }).start();
                }
                //用于存储聊天信息
                SharedPreferences.Editor editor = getSharedPreferences("save_data",MODE_PRIVATE).edit();
                editor.putString("save_data",receiveContent.getText().toString());
                editor.apply();
                editText.setText("");
            }
        });

        EventBus.getDefault().register(this);
    }



    //用户输入对方的IP
    private void showInputIPDialog() {
        editIPAddr=new EditText(MainActivity.this);
        AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
        builder.setView(editIPAddr);
        builder.setTitle("输入对方IP地址");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setNegativeButton("清除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setCancelable(false);
        final AlertDialog dialog=builder.create();
        dialog.show();
        if(dialog.getButton(AlertDialog.BUTTON_POSITIVE)!=null) {
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String ip=editIPAddr.getText().toString();
                    if(!TextUtils.isEmpty(ip)){
                        //正则表达式判断用户输入的IP地址是否合法(cv)
                        String REGEX = "((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))";
                        Pattern pattern = Pattern.compile(REGEX);
                        Matcher matcher = pattern.matcher(ip);
                        boolean b=matcher.matches();
                        if(b){
                            try {
                                transformWords=new CommunicateWordsWithUDP(ip);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        transformWords.ServerReceviedByUdp();
                                    }
                                }).start();
                                Toast.makeText(MainActivity.this,"发消息试试看吧～",Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            } catch (SocketException e) {
                                e.printStackTrace();
                                Toast.makeText(MainActivity.this,"非法的ip地址！",Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            Toast.makeText(MainActivity.this,"非法的ip地址！",Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        Toast.makeText(MainActivity.this,"ip地址不能为空！",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        if(dialog.getButton(AlertDialog.BUTTON_NEGATIVE)!=null) {
            dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editIPAddr.setText("");
                }
            });
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isIPReady){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    transformWords.ServerReceviedByUdp();
                }
            }).start();
        }
    }

    private void initView() {
        editText= (EditText) findViewById(R.id.et_send_content);
        send= (Button) findViewById(R.id.btn_send);
        scrollView= (ScrollView) findViewById(R.id.scrollView);
        receiveContent= (TextView) findViewById(R.id.tv_receive_content);
        editText.addTextChangedListener(mTextWatcher);
        send.setClickable(false);
    }


    //onDestroy()方法记得关闭socket连接，避免端口持续占用
    //解注册EventBus
    @Override
    protected void onDestroy() {
        super.onDestroy();
        transformWords.disconnect();
        EventBus.getDefault().unregister(this);
    }


    //收到消息后做处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showWords(com.example.udp_test.WordsEvent wordsEvent){
        if(!TextUtils.isEmpty(wordsEvent.getWords())){
            receiveContent.append("\n");
            receiveContent.append(Html.fromHtml("<font><strong><em>他:</em></strong></font>"));
            receiveContent.append("\n");
            receiveContent.append(wordsEvent.getWords());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
    }
}
